package com.foxaweb.pageflip
{
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.display.Shape;
	import flash.geom.Point;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	
	public class Book extends Sprite
	{
		private var bmpPages:Array;
		private var flipPages:Array;
		
		private var _leftPages:Number;
		private var _rightPages:Number;
		
		
		public function Book(){
			bmpPages = new Array();
		}
		
		public function addPage(bmp:BitmapData):void{
			bmpPages.push(bmp);	
		}
		
		public function create():void{
			var page:Shape;
			var flip:Object;
			var i:Number = 0;
			var j:Number = 1;

			flipPages = new Array();
			
			while(i<bmpPages.length){
				page = new Shape();
				flip = PageFlip.computeFlip( 	new Point(bmpPages[i].width,bmpPages[i].height),
												new Point(1,1),
												bmpPages[i].width,
												bmpPages[i].height,
												true,
												1);
												
				PageFlip.drawBitmapSheet( flip, page, bmpPages[i],bmpPages[j]);
				
				flipPages.push(new Page(page,bmpPages[i],bmpPages[j]));
				//this.addChild(new Page(page,bmpPages[i],bmpPages[j]));
				i+=2;
				j+=2; 		
			}
			
			for(i=flipPages.length-1; i>=0; i--){
				flipPages[i].addEventListener("pageSelected", disableEventListener);
				flipPages[i].addEventListener("pageDeselected", enableEventListener);
				this.addChild(flipPages[i]);	
			}
			_rightPages = flipPages.length;
			_leftPages = 0
		}
		
		
		public function enableEventListener(evt:Event):void{
			for(var i:String in flipPages){
				flipPages[i].eventActivate = true;
				
				if(evt.target == flipPages[i]){
					if(this.mouseX > (flipPages[i]._width/2)){
						this.setChildIndex(flipPages[i],_rightPages);
						trace("childIndex",_rightPages);
						if(_leftPages == 0) this.dispatchEvent(new Event("noLeftPage"));
						_rightPages++;
					}else{
						_leftPages++;
					}		
				}
			}
			trace("enable", _leftPages, _rightPages);
		}
		
		public function disableEventListener(evt:Event):void{
			trace("disable", _leftPages, _rightPages);			
			for(var i:String in flipPages){
				if(evt.target != flipPages[i]) flipPages[i].eventActivate = false;
				else{
					//trace(flipPages[i].width , flipPages[i]._width/2);
					if(this.mouseX > flipPages[i]._width/2 || _leftPages == 0){ if(_rightPages!=0)_rightPages--;}
					else if(_leftPages!=0)_leftPages-- ; 
				 	
				 	this.setChildIndex(flipPages[i],this.numChildren-1);
				}			
			}
		}
		
		override public function toString():String{
			return "[object Book]";	
		}
	}
}